﻿namespace BEGDC.CC.Web.EZVisit.Controls
{
    #region Using Directives

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web.UI.WebControls;
    using ASBCC.Database.Entity;
    using ASBCC.Database.Service;
    using BL.CCFlow.CR;
    using BL.Common;
    using BL.Workflow;
    using Utility.Castle;

    #endregion

    public partial class EZVRequestFeedback : EZVRequestBaseControl
    {
        private readonly ICR crService = (ICR)AppContainer.Instance[ServiceConst.CRService];

        protected override void SetViewData()
        {
            if (this.EZVisitApplication == null || this.EZVisitApplication.IsDomestic == null)
            {
                return;
            }

            this.lblCustomerName.Text = this.EZVisitApplication.Company;
            this.lblScoreA.Text = this.hidScoreA.Value = "6";
            this.lblScoreB.Text = this.hidScoreB.Value = "6";
            this.lblVenue.Text = this.EZVisitApplication.IsDomestic.Value ? this.EZVisitApplication.DomesticDesc : this.EZVisitApplication.OverseaDesc;

            this.BindQuestions();

            var feedbacks = this.GetFeedBack();

            if (feedbacks.Count == 0)
            {
                return;
            }

            var feedback = feedbacks[0];

            this.edt_SuggestionA.Text = this.vw_SuggestionA.Text = feedback.CommentA;
            this.edt_SuggestionB.Text = this.vw_SuggestionB.Text = feedback.CommentB;
            this.lblScoreA.Text = this.hidScoreA.Value = feedback.ScoreA.Value.ToString();
            this.lblScoreB.Text = this.hidScoreB.Value = feedback.ScoreB.Value.ToString();

            this.BindAnswers(feedback.FeedBackID.GetValueOrDefault(0));
        }

        protected override void SetVisibility()
        {
            base.SetVisibility();

            this.SetDataGridItemsVisibility(this.dgPartA, "A");
            this.SetDataGridItemsVisibility(this.dgPartB, "B");
        }

        public override void Save(EZVisitApplicationTableEntity app)
        {
            if (app == null || app.AppID == null)
            {
                return;
            }

            base.Save(app);

            int feedbackId = this.SaveFeedback();

            this.SaveAnswers(feedbackId);

            this.lblScoreA.Text = this.hidScoreA.Value;
            this.lblScoreB.Text = this.hidScoreB.Value;
        }

        private int SaveFeedback()
        {
            var feedbacks = this.GetFeedBack();

            var feedback = feedbacks.Count != 0 ? feedbacks[0] : new EZVisitFeedBackTableEntity { AppID = this.EZVisitApplication.AppID };

            feedback.ScoreA = Convert.ToDecimal(this.hidScoreA.Value);
            feedback.ScoreB = Convert.ToDecimal(this.hidScoreB.Value);
            feedback.ScoreC = 0;
            feedback.CommentA = this.edt_SuggestionA.Text;
            feedback.CommentB = this.edt_SuggestionB.Text;
            feedback.IsSuggestion = false;

            if (feedback.FeedBackID == null)
            {
                EZVisitFeedBackManager.Insert(feedback);
            }
            else
            {
                EZVisitFeedBackManager.Update(feedback);
            }

            return feedback.FeedBackID.Value;
        }

        private void SaveAnswers(int feedbackId)
        {
            var oldAnswers = EZVisitAnswerManager.SelectByCondition(string.Format("FeedBackID={0}", feedbackId)).OfType<EZVisitAnswerTableEntity>();
            var newAnswers = GetAnswersFromDataGrid(this.dgPartA, "A", feedbackId).Union(GetAnswersFromDataGrid(this.dgPartB, "B", feedbackId));

            bool haveAnswers = oldAnswers.Count() != 0;

            foreach (EZVisitAnswerTableEntity answer in newAnswers)
            {
                if (haveAnswers)
                {
                    var oldAnswer = oldAnswers.FirstOrDefault(c => c.QuestionID == answer.QuestionID);

                    if (oldAnswer == null)
                    {
                        continue;
                    }

                    answer.AnswerID = oldAnswer.AnswerID;

                    EZVisitAnswerManager.Update(answer);
                }
                else
                {
                    EZVisitAnswerManager.Insert(answer);
                }
            }
        }

        private EZVisitFeedBackTableEntitySet GetFeedBack()
        {
            string condition = string.Format("AppID={0}", this.EZVisitApplication.AppID);

            return EZVisitFeedBackManager.SelectByCondition(condition);
        }

        private void BindQuestions()
        {
            //Bind PART_A questions
            DataTable dtPartA = this.crService.GetSurveyQuestions(WorkflowTypes.EZV, "PartA-Visit", true);

            if (dtPartA != null && dtPartA.Rows.Count > 0)
            {
                this.dgPartA.DataSource = dtPartA;
                this.dgPartA.DataBind();
                this.hidScoreARows.Value = dtPartA.Rows.Count.ToString();
            }

            //Bind PART_B questions
            DataTable dtPartB = this.crService.GetSurveyQuestions(WorkflowTypes.EZV, "PartB-Reception", true);

            if (dtPartB != null && dtPartB.Rows.Count > 0)
            {
                this.dgPartB.DataSource = dtPartB;
                this.dgPartB.DataBind();
                this.hidScoreBRows.Value = dtPartB.Rows.Count.ToString();
            }
        }

        private void SetDataGridItemsVisibility(DataGrid dg, string a)
        {
            foreach (DataGridItem row in dg.Items)
            {
                var ddlScore = (DropDownList)row.FindControl("ddlScore" + a);
                var lblScroe = (Label)row.FindControl("lblScore" + a);
                var txtComment = (TextBox)row.FindControl("txtComment" + a);
                var lblComment = (Label)row.FindControl("lblComment" + a);

                ddlScore.Visible = txtComment.Visible = this.Editable;
                lblScroe.Visible = lblComment.Visible = !this.Editable;
            }
        }

        private void BindAnswers(int feedbackId)
        {
            string condition = string.Format("FeedBackID={0}", feedbackId);
            var answers = EZVisitAnswerManager.SelectByCondition(condition).OfType<EZVisitAnswerTableEntity>();

            if (answers.Count() == 0)
            {
                return;
            }

            SetDataGridItemsData(answers, this.dgPartA, "A");
            SetDataGridItemsData(answers, this.dgPartB, "B");
        }

        private static IEnumerable<EZVisitAnswerTableEntity> GetAnswersFromDataGrid(DataGrid dg, string a, int feedbackId)
        {
            return from DataGridItem row in dg.Items
                   let questionId = Convert.ToInt32(row.Cells[0].Text)
                   let ddlScore = (DropDownList)row.FindControl("ddlScore" + a)
                   let txtComment = (TextBox)row.FindControl("txtComment" + a)
                   select new EZVisitAnswerTableEntity { FeedBackID = feedbackId, QuestionID = questionId, Score = ddlScore.SelectedValue, Comment = txtComment.Text };
        }

        private static void SetDataGridItemsData(IEnumerable<EZVisitAnswerTableEntity> answers, DataGrid dg, string a)
        {
            foreach (DataGridItem row in dg.Items)
            {
                int questionId = Convert.ToInt32(row.Cells[0].Text);
                var answer = answers.FirstOrDefault(c => c.QuestionID == questionId);

                if (answer == null)
                {
                    continue;
                }

                var ddlScore = (DropDownList)row.FindControl("ddlScore" + a);
                var lblScore = (Label)row.FindControl("lblScore" + a);
                var txtComment = (TextBox)row.FindControl("txtComment" + a);
                var lblComment = (Label)row.FindControl("lblComment" + a);

                ddlScore.SelectedValue = lblScore.Text = answer.Score;
                txtComment.Text = lblComment.Text = answer.Comment;
            }
        }
    }
}